package com.bjpowernode.p2p.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.bjpowernode.common.constant.Constants;
import com.bjpowernode.common.util.ResultMap;
import com.bjpowernode.p2p.model.user.User;
import com.bjpowernode.p2p.service.BInfoService;
import com.bjpowernode.p2p.service.FinanceAccountService;
import com.bjpowernode.p2p.service.LoanService;
import com.bjpowernode.p2p.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:InvestController
 * Package:com.bjpowernode.p2p.web
 * Description: 处理投资有关的请求
 *
 * @date:2021/7/21 17:16
 * @author:动力节点
 */
@Controller
public class InvestController {
    @Reference(interfaceClass = LoanService.class,version ="1.0-SNAPSHOT",check = false,timeout = 15000)
    private LoanService loanService;

    @Reference(interfaceClass = BInfoService.class,check = false,version = "1.0-SNAPSHOT",timeout = 15000)
    private BInfoService bInfoService;

    @Reference(interfaceClass = FinanceAccountService.class,check = false,version = "1.0-SNAPSHOT",timeout = 15000)
    private FinanceAccountService financeAccountService;

    @Reference(interfaceClass = UserService.class,check = false,version = "1.0-SNAPSHOT",timeout = 15000)
    private UserService userService;

    @RequestMapping("/invest")
    @ResponseBody
    public Map investInfo(HttpServletRequest request,
                          @RequestParam(value = "money",required = true) Double money,
                          @RequestParam(value = "loanId",required = true) Integer loanId){
        System.out.println();
        Map<String, Object> paramMap =new HashMap<>();
        paramMap.put("money",money);
        paramMap.put("loanId",loanId);
        User user = (User) request.getSession().getAttribute(Constants.USER);
        paramMap.put("uid",user.getId());
        System.out.println(paramMap);
       //进行投资：修改金融账户余额，产品剩余可投金额，投资投资表的投资信息
      //交给业务处理层去处理，并开启事务
      int result = loanService.invest(paramMap);
      if(result>=0){
          //更新session中对象的内容
          User sessionUser = (User) request.getSession().getAttribute(Constants.USER);
          //再次查询session信息：更新session中的user信息
          User updateUser =userService.queryUser(sessionUser.getId());
          request.getSession().setAttribute(Constants.USER,updateUser);
          return ResultMap.success();
      }else{
          return ResultMap.error("投资失败！");
      }
    }
}
